<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q" ref='searchRef'>
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option :label="item.cate_name" :value="item.id" v-for="item in cateList" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="search">筛选</el-button>
            <el-button type="info" size="small" @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="pubDialogVisible = true">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="artList" border stripe>
        <el-table-column label="文章标题">
          <template  v-slot="{row}">
            <el-link type="primary" @click="getArtDetail(row.id)">{{row.title}}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="文章分类" prop="cate_name"></el-table-column>
        <el-table-column label="发表时间" >
          <template v-slot="{row}">
             {{ row.pub_date | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button type="danger" size="mini" @click="delArticle(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <!--
        current-page: 当前页码值（现在处于第几页）
        page-sizes: 每页显示条数列表
        page-size: 当前每页显示的条数
        layout: 分页显示 布局
        total: 数据总条数

        size-change: 每页显示的条数发生改变时触发
        current-change: 页码值改变时触发
       -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 发表文章弹出框 -->
    <el-dialog
        title="发表文章"
        :visible.sync="pubDialogVisible"
        fullscreen
        :before-close="handleBeforeClose"
        @close="handleClose">

        <el-form :model="pubForm" :rules="pubRules" ref="pubRef" label-width="100px">
            <!-- 标题 -->
            <el-form-item label="文章标题" prop="title">
                <el-input v-model="pubForm.title"></el-input>
            </el-form-item>
            <!-- 分类 -->
            <el-form-item label="文章分类" prop="cate_id">
                <el-select v-model="pubForm.cate_id" placeholder="请选择文章分类" style="width:100%">
                    <el-option :label="item.cate_name" :value="item.id" v-for="item in cateList" :key="item.id"></el-option>
                </el-select>
            </el-form-item>
            <!-- 富文本编辑器实现文章内容 -->
            <el-form-item label="文章内容" prop="content">
                <quill-editor v-model="pubForm.content"></quill-editor>
            </el-form-item>
            <!-- 文章封面 -->
            <el-form-item label="文章封面">
              <img src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
              <br />
              <input type="file" style="display: none;" accept="image/*" ref="iptFile" @change="onFileChange"/>
              <el-button type="text" @click="chooseImg">+ 选择封面</el-button>
            </el-form-item>
            <!-- 按钮 -->
            <el-form-item>
              <el-button type="primary" @click="pubArticle('已发布')">发布</el-button>
              <el-button type="info" @click="pubArticle('草稿')">存为草稿</el-button>
            </el-form-item>

        </el-form>

    </el-dialog>

    <!-- 文章详情弹出框 -->
    <el-dialog
      title="文章详情"
      :visible.sync="artDetailVisible"
      width="80%"
      >
      <h1 class="title">{{ artDetail.title }}</h1>

      <div class="info">
        <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
        <span>发布时间：{{ artDetail.pub_date | dateFormat }}</span>
        <span>所属分类：{{ artDetail.cate_name }}</span>
        <span>状态：{{ artDetail.state }}</span>
      </div>

      <el-divider></el-divider>

      <img :src="'http://www.liulongbin.top:3008'+artDetail.cover_img" >

      <div v-html="artDetail.content"></div>
    </el-dialog>
  </div>
</template>

<script>
import defaultImg from '@/assets/images/cover.jpg'
export default {
  name: 'ArtList',
  data () {
    return {
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      // 发表文章的显示与隐藏
      pubDialogVisible: false,

      //   发表文章表单数据
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: null,
        state: ''
      },

      //   发表文章表单数据校验规则
      pubRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur' }
        ],
        cate_id: [{ required: true, message: '请选择文章标题', trigger: 'blur' }],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ]
      },

      // 文章分类
      cateList: [],

      // 文章列表
      artList: [],

      // 文章总条数
      total: 0,

      // 文章详情
      artDetail: {},

      // 文章详情显示与隐藏
      artDetailVisible: false
    }
  },
  methods: {
    async handleBeforeClose (done) {
      const res = await this.$confirm('你确定要关闭发表文章对话框吗').catch(err => err)
      if (res === 'cancel') return
      done() // done()代表放行,关闭
    },

    // 获取文章分类
    async initCateList () {
      const { data: res } = await this.$http.get('/my/cate/list')
      //   console.log(res)
      if (res.code === 0) {
        this.cateList = res.data
      }
    },

    // 文章封面
    chooseImg () {
      this.$refs.iptFile.click()
    },
    onFileChange (e) {
      // console.dir(e.target.files)
      const files = e.target.files

      if (files.length === 0) {
        // 没有选择图片
        this.pubForm.cover_img = null
        this.$refs.imgRef.src = defaultImg // 图片模块
      } else {
        // 选择了图片
        this.pubForm.cover_img = files[0]
        // 实现图片预览   file[0]图片对象  =>  img展示(1.base64   2.图片地址URL)
        const url = URL.createObjectURL(files[0]) // blob:http://localhost:8080/67b712fb-05d1-457d-95e9-af1e170edc26
        // console.log(url)
        // 将url路径赋值给img的src属性
        this.$refs.imgRef.src = url
      }
    },

    // 发布文章
    pubArticle (state) {
      this.pubForm.state = state

      // 手动校验
      this.$refs.pubRef.validate(async valid => {
        if (!valid) return this.$message.warning('请完善文章信息')
        if (!this.pubForm.cover_img) return this.$message.warning('请设置文章封面')

        // 数据类型转换
        const fd = new FormData()
        // for (const k in this.pubForm) {
        //   fd.append(k, this.pubForm[k])
        // }
        // Object.keys(对象) => 数组 对象中所有的键  ['title', 'cate_id', 'content', 'cover_img', 'state']
        Object.keys(this.pubForm).forEach(item => {
          fd.append(item, this.pubForm[item])
        })

        // console.dir(fd)
        // fd.forEach((value, key) => {
        //   console.log(key, value)
        // })

        // axios发送请求
        const { data: res } = await this.$http.post('/my/article/add', fd)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)

        // 关闭弹出框
        this.pubDialogVisible = false
        // 重置文章列表 未完待续
        this.initArtList()
      })
    },

    // 关闭弹出框重置表单数据
    handleClose () {
      this.$refs.pubRef.resetFields()
      this.pubForm.cover_img = null
      this.$refs.imgRef.src = defaultImg
    },

    // 获取文章列表
    async initArtList () {
      const { data: res } = await this.$http.get('/my/article/list', { params: this.q })
      if (res.code === 0) {
        this.artList = res.data
        this.total = res.total
      }
    },

    // 分页 条数改变
    handleSizeChange (newSize) {
      // 新每页条数赋值给q.pagesize
      this.q.pagesize = newSize
      // 再重新axios获取数据
      this.initArtList()
    },

    // 分页 页码改变
    handleCurrentChange (newPage) {
      // 新页码值赋值给q.pagenum
      this.q.pagenum = newPage
      // 再重新axios获取数据
      this.initArtList()
    },

    // 筛选
    search () {
      this.q.pagenum = 1
      this.initArtList()
    },

    // 重置筛选
    reset () {
      // console.log(123)
      // this.$refs.searchRef.resetFields()

      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }

      this.initArtList()
    },

    // 根据id获取文章详情
    async getArtDetail (id) {
      const { data: res } = await this.$http.get('/my/article/info', { params: { id } })
      this.artDetail = res.data

      this.artDetailVisible = true
    },

    //  根据id删除文章
    async delArticle (id) {
      // try {
      //   await this.$confirm('确定要永久删除该文章吗')

      //   // 这里的代码就是点击的确定按钮
      //   const { data: res } = await this.$http.delete('/my/article/info', { params: { id } })
      //   if (res.code !== 0) return this.$message.error(res.message)
      //   this.$message.success(res.message)

      //   this.initArtList()
      // } catch (err) {
      //   return err
      // }

      const result = await this.$confirm('确定要永久删除该文章吗').catch(err => err)
      if (result !== 'confirm') return

      const { data: res } = await this.$http.delete('/my/article/info', { params: { id } })
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)

      // 删除优化 当页面中只有一条数据时,删除后展示上一页的数据
      if (this.artList.length === 1 && this.q.pagenum > 1) {
        this.q.pagenum--
      }

      this.initArtList()
    }
  },
  created () {
    this.initCateList()
    this.initArtList()
  }

}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}

// vue组件中,不能修改子组件内部的样式
// 如果想修改子组件中样式可以使用 vue中css样式穿透
// 语法: /deep/ 或 ::v-deep

::v-deep .ql-editor{
    height: 250px;
}

// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}

.el-pagination {
  margin-top:15px;
}

.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}
</style>
